package edu.whu.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.whu.demo.dao.ItemMybatisPlusMapper;
import edu.whu.demo.entity.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ItemService {
    @Autowired
    ItemMybatisPlusMapper mapper;

    public Item addItem(Item item) {
        mapper.insert(item);
        return mapper.selectById(item.getId());
    }

    public Item getItem(long id) {
        return mapper.selectById(id);
    }

    public List<Item> findItems(String name, Boolean surplus) {
        LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<Item>();
        if(name == null && surplus == null)
            return mapper.selectList(null);
        else if(surplus == null)
            lqw.like(Item::getName,name);
        else if(name == null) {
            if(surplus)
                lqw.gt(true, Item::getCount, 0);
            else
                lqw.gt(false, Item::getCount, 0);
        }
        else {
            if(surplus)
                lqw.ge(Item::getName, name).gt(true, Item::getCount, 0);
            else
                lqw.ge(Item::getName, name).gt(false, Item::getCount, 0);
        }
        return mapper.selectList(lqw);
    }

    public void updateItem(long id, Item item) {
        mapper.updateById(item);
    }

    public void deleteItem(long id) {
        mapper.deleteById(id);
    }

    public List<Item> getAll(){
        List<Item> itemList = mapper.selectList(null);
        return itemList;
    }
}
